package com.gogowan.agroenterprise;

import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.Enum.Temp;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask.AsyncLoadListener;
import com.gogowan.agroenterprise.contorl.WeakRefAsyncTask.InterActionModel;
import com.gogowan.agroenterprise.model.BoxBindCodeRequest;
import com.gogowan.agroenterprise.model.BoxBindCodeResult;
import com.gogowan.agroenterprise.model.CodeActivationInfo;
import com.gogowan.agroenterprise.model.CodeActivationResultInfo;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.MaterialBatch;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.OperationTypeDict;
import com.gogowan.agroenterprise.model.SplitBoxGetCodeRequest;
import com.gogowan.agroenterprise.model.SplitBoxGetCodeResult;
import com.gogowan.agroenterprise.model.Version;
import com.gogowan.agroenterprise.model.VersionClientInfo;
import com.gogowan.agroenterprise.storage.DealerListActivity;
import com.gogowan.agroenterprise.storage.HistoryActivity;
import com.gogowan.agroenterprise.storage.InStorageActivity;
import com.gogowan.agroenterprise.storage.InventoryActivity;
import com.gogowan.agroenterprise.storage.OutStorageActivity;
import com.gogowan.agroenterprise.storage.PackActivity;
import com.gogowan.agroenterprise.storage.UnpackActivity;
import com.gogowan.agroenterprise.storage.WarehouseListActivity;
import com.gogowan.agroenterprise.utils.PalUtils;
import com.gogowan.agroenterprise.utils.Utils;

public class MainActivity extends BaseActivity implements AsyncLoadListener {

	private RelativeLayout operation;
	private RelativeLayout spector;
	private RelativeLayout sales;
	// private Button activate;
	// private Button supplyAndDemand;
	private TextView exit;
	// private TextView op, spec, sale, active, sad, exittext;
	// private TextPaint tp;
	private boolean isNew;
	private ProgressDialog progressDialog;
	private long enterpriseId;

	// added on 20170109
	private WeakRefAsyncTask weakRefAsyncTask = new WeakRefAsyncTask(this);
	private static final int BOX_RQT = 1;
	private static final int GIFT_RQT = 2;
	private static final int UNPACK_RQT = 3;
	private static final int BOX_RQC = 199301;
	private static final int GIFT_RQC = 199302;
	private static final int UNPACK_RQC = 199303;
	private String scanCode = "";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);

		operation = (RelativeLayout) findViewById(R.id.main_rl_operation);
		spector = (RelativeLayout) findViewById(R.id.main_rl_spector);
		sales = (RelativeLayout) findViewById(R.id.main_rl_sales);
		exit = (TextView) findViewById(R.id.main_btn_exit);
		UpdateAsync updateAsync = new UpdateAsync();
		updateAsync.execute();

		
		isNew = MyApplication.mSettings.getBoolean("isNew", false);
		enterpriseId = MyApplication.mSettings.getLong("enterpriseid", 0);

		/**
		 * 作业管理
		 */
		operation.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent(MainActivity.this,
				// OperationActivity.class);
				// startActivity(intent);
				// overridePendingTransition(R.anim.push_left_in,
				// R.anim.push_left_out);


//				if (operationdict.length == 0) {
//					Toast.makeText(MainActivity.this, "暂无作业类型",
//							Toast.LENGTH_LONG).show();
//				} else {
//					Intent intent = new Intent(Intents.Scan.ACTION);
//					intent.putExtra("type", 2);
//					startActivityForResult(intent, 100);
//				}

			}
		});

		/**
		 * 巡检记录
		 */
		spector.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent intent = new Intent(MainActivity.this,
				// SpectorActivity.class);
				// startActivity(intent);
				// overridePendingTransition(R.anim.push_left_in,
				// R.anim.push_left_out);

				Intent intent = new Intent(Intents.Scan.ACTION);
				intent.putExtra("type", 2);
				startActivityForResult(intent, 99);
			}
		});

		sales.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						SalesActivity.class);
				startActivity(intent);
			}
		});

		// // 包装附码
		// activate.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// Intent intent = new Intent(MainActivity.this,
		// ActivateActivity.class);
		// startActivity(intent);
		// overridePendingTransition(R.anim.push_left_in,
		// R.anim.push_left_out);
		// }
		// });
		//
		// supplyAndDemand.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// Intent intent = new Intent(MainActivity.this,
		// SupplyMainActivity.class);
		// startActivity(intent);
		// overridePendingTransition(R.anim.push_left_in,
		// R.anim.push_left_out);
		// }
		// });

		exit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ShowLogoutDialog("退出当前帐号", "确定退出当前帐号吗？", "确定退出", "取消", null,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								try {
									Intent intent = new Intent(
											MainActivity.this,
											LoginActivity.class);
									startActivity(intent);
									MainActivity.this.finish();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						});
			}
		});

		// added on 20170109
		// 装箱
		findViewById(R.id.main_zx_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intents.Scan.ACTION);
				startActivityForResult(intent, BOX_RQC);
			}
		});
		// 装盒
		findViewById(R.id.main_zh_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intents.Scan.ACTION);
				startActivityForResult(intent, GIFT_RQC);
			}
		});
		// 包装记录
		findViewById(R.id.main_bzjl_rl).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						startActivity(new Intent(MainActivity.this,
								HistoryActivity.class));
					}
				});
		// 拆箱(拆盒)
		findViewById(R.id.main_cx_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intents.Scan.ACTION);
				startActivityForResult(intent, UNPACK_RQC);
			}
		});
		// 经销商管理
		findViewById(R.id.main_jxsgl_rl).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						startActivity(new Intent(MainActivity.this,
								DealerListActivity.class));
					}
				});
		// //////////////////////////////////////////
		// 仓库管理
		findViewById(R.id.main_ckgl_rl).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						startActivity(new Intent(MainActivity.this,
								WarehouseListActivity.class));
					}
				});

		// 入库
		findViewById(R.id.main_rk_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this,
						InStorageActivity.class));
			}
		});

		// 出库
		findViewById(R.id.main_ck_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this,
						OutStorageActivity.class));
			}
		});

		// 仓储
		findViewById(R.id.main_cc_rl).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this,
						InventoryActivity.class));
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {

			if (requestCode == 100) {
				String contents = data.getStringExtra("SCAN_RESULT").trim();
				// contents = Utils.getCodeStr(contents);

				CodeActivationInfo activationInfo = new CodeActivationInfo();
				activationInfo.setStartcode(contents);
				activationInfo.setEnterpriseid(enterpriseId);
				activationInfo.setIsnew(isNew);
				progressDialog = ProgressDialog.show(MainActivity.this, "提示",
						"正在查询....", true, false);
				PaimaAsyn paimaAsyn = new PaimaAsyn();
				paimaAsyn.execute(activationInfo);

			}

			if (requestCode == 99) {
				String contents = data.getStringExtra("SCAN_RESULT").trim();
				contents = Utils.getCodeStr(contents);

				CodeActivationInfo activationInfo = new CodeActivationInfo();
				activationInfo.setStartcode(contents);
				activationInfo.setEnterpriseid(enterpriseId);
				activationInfo.setIsnew(isNew);
				progressDialog = ProgressDialog.show(MainActivity.this, "提示",
						"正在查询....", true, false);
				XJPaimaAsyn paimaAsyn = new XJPaimaAsyn();
				paimaAsyn.execute(activationInfo);
			}

			// added on 20170109
			// 箱码
			if (requestCode == BOX_RQC) {
				scanCode = Utils.getCodeStr(data.getStringExtra(
						Intents.Scan.RESULT).trim());
				requestPackScanCode(1, scanCode);
			}

			// 盒码
			if (requestCode == GIFT_RQC) {
				scanCode = Utils.getCodeStr(data.getStringExtra(
						Intents.Scan.RESULT).trim());
				requestPackScanCode(2, scanCode);
			}

			// 拆箱
			if (requestCode == UNPACK_RQC) {
				String contents = Utils.getCodeStr(data.getStringExtra(
						Intents.Scan.RESULT).trim());
				requestUnpackScanCode(contents);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void showFinishDialog() {
		new AlertDialog.Builder(MainActivity.this).setTitle("提示")
				.setMessage("数据初始化失败").setCancelable(false)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						MainActivity.this.finish();
					}
				}).create().show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			ShowExitActivityDialog("退出系统吗?");
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 作业管理交互
	 * 
	 * @author Administrator
	 * 
	 */
	private class PaimaAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(MainActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(MainActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {

					CodeActivationResultInfo codeActivationResultInfo = (CodeActivationResultInfo) Utils
							.fromJSON(string, CodeActivationResultInfo.class);

					if (codeActivationResultInfo.getResult() == 2010) {
						List<MaterialBatch> batches = codeActivationResultInfo
								.getBatchList();
						if (batches == null || batches.size() == 0) {
							Toast.makeText(MainActivity.this, "批次列表空",
									Toast.LENGTH_LONG).show();
							return;
						} else {
							try {
								OperationTypeDict operationType = codeActivationResultInfo
										.getOperationType();
								Intent intent = new Intent(MainActivity.this,
										OperationActivity.class);

								if (operationType == null) {
									intent.putExtra("typeId", -1);
									intent.putExtra("typeStr", "");
								} else {
									intent.putExtra("typeId",
											operationType.getOperationtypeid());
									intent.putExtra("typeStr",
											operationType.getOperationtype());
								}
								intent.putExtra("batches", string);
								startActivity(intent);
							} catch (Exception e) {
								// TODO: handle exception
								e.printStackTrace();
							}

						}
					} else {
						Toast.makeText(MainActivity.this,
								codeActivationResultInfo.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {

			CodeActivationInfo request = (CodeActivationInfo) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(2000, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 巡检记录交互
	 * 
	 * @author Administrator
	 * 
	 */
	private class XJPaimaAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(MainActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(MainActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					CodeActivationResultInfo codeActivationResultInfo = (CodeActivationResultInfo) Utils
							.fromJSON(string, CodeActivationResultInfo.class);

					if (codeActivationResultInfo.getResult() == 3010) {
						List<MaterialBatch> batches = codeActivationResultInfo
								.getBatchList();
						if (batches == null || batches.size() == 0) {
							Toast.makeText(MainActivity.this, "批次列表空",
									Toast.LENGTH_LONG).show();
							return;
						} else {
							Intent intent = new Intent(MainActivity.this,
									SpectorActivity.class);
							// intent.putParcelableArrayListExtra("batches",
							// (ArrayList<? extends Parcelable>) batches);

							intent.putExtra("batches", string);
							startActivity(intent);
						}
					} else {
						Toast.makeText(MainActivity.this,
								codeActivationResultInfo.getResultinfo(),
								Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			CodeActivationInfo request = (CodeActivationInfo) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(3000, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * 检测是否更新 异步
	 * 
	 * @author Administrator
	 * 
	 */
	public class UpdateAsync extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			/*
			 * 此方法在主线程执行，任务执行的结果作为此方法的参数返回
			 */
			String results = (String) res;
			Message message = stringToMessage(results);// 转换成消息盒子

			if (message == null) {
				// ShowDialog(getString(R.string.js_prompt),getString(R.string.js_internet_fail));
				// 初始化字典
				return;
			}

			String content = Utils.getMessageContent(message);// 消息内容

			Version version = new Version();
			version = (Version) Utils.fromJSON(content, Version.class);

//			int result = version.getResult();
//			String resultinfo = version.getResultinfo();

//			if (result == 1810) {
				String des = version.getDescribe();
				final String updateUrl = version.getUrl().trim();
				final int isforceupdate = version.getIsforceupdate();
				CharSequence charseq = null;
				if (!Utils.isEmpty(des)) {
					charseq = Html.fromHtml(des);
				}
				if (updateUrl.equals("0") || Utils.isEmpty(updateUrl)) {
					// SkipActivity(Main.this,true);
				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							MainActivity.this);
					builder.setTitle("升级");
					if (charseq == null) {
						builder.setMessage(des);
					} else {
						builder.setMessage(charseq);
					}
					builder.setCancelable(false);// 是否可以按BACK键
					builder.setPositiveButton("是",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {

									Intent intent = new Intent();
									intent.setClass(MainActivity.this,
											UpdateActivity.class);
									Bundle mBundle = new Bundle();
									mBundle.putSerializable("token",
											new String[] { updateUrl,
													"" + isforceupdate, "" });
									intent.putExtras(mBundle);
									startActivity(intent);
									MainActivity.this.finish();
								}
							});
					if (isforceupdate!=1)// 非强制升级
					{
						builder.setNegativeButton("否",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// 初始化字典
									}
								});
					}
					builder.create().show();
				}
//			} else if (result == -1810) {
//				// ShowDialog("提示", resultinfo);
//			} else {
//				// 初始化字典
//				// ShowDialog("错误", "未知错误");
//			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {

			VersionClientInfo versioninfo = new VersionClientInfo();
			try {
				versioninfo.setVersioncode(Integer
						.parseInt(getString(R.string.version_code)));
			} catch (NumberFormatException efe) {
				versioninfo.setVersioncode(0);
			}
			versioninfo.setVersion(Utils.getVersionName(MainActivity.this));

			String json = Utils.toJSON(versioninfo);
			int type = Utils.getTempValue(Temp.update);
			Message message = new Message(type, true, json);
			String result = Utils.postCommit(getString(R.string.update_url),
					message);// 提交数据
			return result;
		}
	}

	/**
	 * 获取扫码数据-装箱装盒
	 * 
	 * @param flag
	 *            1 box 2 gift
	 * */
	private void requestPackScanCode(int flag, String scanCode) {
		if (PalUtils.isEmpty(scanCode)) {
			PalUtils.showShortToast(getApplicationContext(),
					getString(R.string.sales_msg_default_status));
			return;
		}
		progressDialog = ProgressDialog.show(MainActivity.this, "提示",
				"正在查询....", true, false);
		BoxBindCodeRequest boxBindCodeRequest = new BoxBindCodeRequest();
		boxBindCodeRequest.setEnterpriseId(enterpriseId);
		boxBindCodeRequest.setBoxCode(scanCode);
		String json = Utils.toJSON(boxBindCodeRequest);
		Message message = new Message(flag == 1 ? PalUtils.MsgType.BoxCode
				: PalUtils.MsgType.PackCode, PalUtils.ENCRYPT, json);
		InterActionModel interActionModel = new InterActionModel();
		interActionModel.setIndex(flag == 1 ? BOX_RQT : GIFT_RQT);
		interActionModel.setUrl(getString(R.string.first_url)
				+ getString(R.string.first_url_page));
		interActionModel.setMessage(message);
		weakRefAsyncTask.execute(interActionModel);
	}

	/**
	 * 获取扫码数据-拆箱拆盒
	 * 
	 * @param
	 *
	 * */
	private void requestUnpackScanCode(String scanCode) {
		if (PalUtils.isEmpty(scanCode)) {
			PalUtils.showShortToast(getApplicationContext(),
					getString(R.string.sales_msg_default_status));
			return;
		}
		progressDialog = ProgressDialog.show(MainActivity.this, "提示",
				"正在查询....", true, false);
		SplitBoxGetCodeRequest boxBindCodeRequest = new SplitBoxGetCodeRequest();
		boxBindCodeRequest.setEnterpriseId(enterpriseId);
		boxBindCodeRequest.setCode(scanCode);
		String json = Utils.toJSON(boxBindCodeRequest);
		Message message = new Message(PalUtils.MsgType.SplitBoxGetCode,
				PalUtils.ENCRYPT, json);
		InterActionModel interActionModel = new InterActionModel();
		interActionModel.setIndex(UNPACK_RQT);
		interActionModel.setUrl(getString(R.string.first_url)
				+ getString(R.string.first_url_page));
		interActionModel.setMessage(message);
		weakRefAsyncTask.execute(interActionModel);
	}

	@Override
	public void onResult(AsyncLoadListener asyncLoadListener, String response,
			int actionId) {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
		if (PalUtils.isEmpty(response)) {
			PalUtils.showShortToast(getApplicationContext(),
					getString(R.string.server_error));
		} else {
			switch (actionId) {
			// 箱码
			case BOX_RQT:
				BoxBindCodeResult boxBindCodeResult = (BoxBindCodeResult) PalUtils
						.getPostResult(response, BoxBindCodeResult.class);
				if (boxBindCodeResult == null) {
					PalUtils.showShortToast(getApplicationContext(),
							getString(R.string.analyse_error));
				} else if (boxBindCodeResult.getResult() > 0) {
					Intent intent = new Intent(this, PackActivity.class);
					intent.putExtra(PalUtils.PACK_MODEL_ITT, boxBindCodeResult);
					intent.putExtra(PalUtils.PACK_TYPE_ITT, 1);
					intent.putExtra(PalUtils.PACK_CODE_ITT, scanCode);
					startActivity(intent);
				} else {
					PalUtils.showShortToast(getApplicationContext(),
							boxBindCodeResult.getResultinfo());
				}
				break;
			// 盒码
			case GIFT_RQT:
				BoxBindCodeResult boxBindCodeResult1 = (BoxBindCodeResult) PalUtils
						.getPostResult(response, BoxBindCodeResult.class);
				if (boxBindCodeResult1 == null) {
					PalUtils.showShortToast(getApplicationContext(),
							getString(R.string.analyse_error));
				} else if (boxBindCodeResult1.getResult() > 0) {
					Intent intent = new Intent(this, PackActivity.class);
					intent.putExtra(PalUtils.PACK_MODEL_ITT, boxBindCodeResult1);
					intent.putExtra(PalUtils.PACK_TYPE_ITT, 2);
					intent.putExtra(PalUtils.PACK_CODE_ITT, scanCode);
					startActivity(intent);
				} else {
					PalUtils.showShortToast(getApplicationContext(),
							boxBindCodeResult1.getResultinfo());
				}
				break;
			// 拆箱拆盒
			case UNPACK_RQT:
				SplitBoxGetCodeResult bindCodeRemoveResult = (SplitBoxGetCodeResult) PalUtils
						.getPostResult(response, SplitBoxGetCodeResult.class);
				if (bindCodeRemoveResult == null) {
					PalUtils.showShortToast(getApplicationContext(),
							getString(R.string.analyse_error));
				} else if (bindCodeRemoveResult.getResult() > 0) {
					Intent intent = new Intent(this, UnpackActivity.class);
					intent.putExtra(PalUtils.PACK_MODEL_ITT,
							bindCodeRemoveResult);
					startActivity(intent);
				} else {
					PalUtils.showShortToast(getApplicationContext(),
							bindCodeRemoveResult.getResultinfo());
				}
				break;
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		weakRefAsyncTask.cancel();
	}

}